﻿using Applay;
using Example.Persistence;
using Example.Persistence.Account;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example.Application.Account
{
    public class AccountService : Service
    {
        private readonly IEntities entities;

        public AccountService(IEntities entities)
        {
            this.entities = entities;
        }

        public bool LogIn(LogInModel model)
        {
            if (ModelState.IsValid)
            {
                var hashedPassword = HashPassword(model.Email, model.Password);

                if (!this.entities.Of<User>().Any(u => u.Email == model.Email && u.HashedPassword == hashedPassword))
                {
                    ModelState.AddError("Login failed.");
                }
            }

            return ModelState.IsValid;
        }
        
        public bool Register(RegisterModel model)
        {
            if (this.entities.Of<User>().Any(u => u.Email == model.Email))
            {
                ModelState.AddError("A user with the same email address already exists.", "Email");
            }

            if (ModelState.IsValid)
            {
                var user = new User
                {
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    Email = model.Email,
                    HashedPassword = HashPassword(model.Email, model.Password)
                };

                this.entities.Of<User>().Add(user);
                this.entities.SaveChanges();

                return true;
            }

            return false;
        }

        private static string HashPassword(string email, string password)
        {
            var algorithm = new System.Security.Cryptography.SHA512Cng();

            var data = Encoding.Default.GetBytes(email.ToLower() + password);
            var hash = algorithm.ComputeHash(data);

            return Convert.ToBase64String(hash);
        }
    }
}
